import api from './api'

export interface KafkaConfig {
  bootstrap_servers: string
  security_protocol: string
  sasl_mechanism: string
  sasl_username?: string
  sasl_password?: string
  api_version?: string
}

export interface KsqlConfig {
  ksql_server_url: string
  ksql_username?: string
  ksql_password?: string
  ksql_timeout: number
  ksql_enabled: boolean
}

export interface TestResult {
  success: boolean
  message: string
  brokers?: number
  api_version?: string
  version?: string
}

export const settingsApi = {
  // Kafka配置相关
  async saveKafkaConfig(config: KafkaConfig): Promise<{ success: boolean; message: string }> {
    return api.post('/settings/kafka', config)
  },

  async getKafkaConfig(): Promise<KafkaConfig> {
    return api.get('/settings/kafka')
  },

  async testKafkaConnection(config: KafkaConfig): Promise<TestResult> {
    return api.post('/settings/kafka/test', config)
  },

  // KSQL配置相关
  async saveKsqlConfig(config: KsqlConfig): Promise<{ success: boolean; message: string }> {
    return api.post('/settings/ksql', config)
  },

  async getKsqlConfig(): Promise<KsqlConfig> {
    return api.get('/settings/ksql')
  },

  async testKsqlConnection(config: KsqlConfig): Promise<TestResult> {
    return api.post('/settings/ksql/test', config)
  }
}

// KSQL查询相关接口
export interface KsqlQueryRequest {
  ksql: string
  streamsProperties?: Record<string, any>
  sessionVariables?: Record<string, any>
}

export interface KsqlQueryResult {
  success: boolean
  data?: any[]
  error?: string
  execution_time?: number
  row_count?: number
  query_id?: string
  command_status?: any
}

export const ksqlApi = {
  // 执行KSQL查询
  async executeQuery(request: KsqlQueryRequest): Promise<KsqlQueryResult> {
    return api.post('/ksql/query', request)
  },

  // 获取KSQL服务器信息
  async getInfo(): Promise<any> {
    return api.get('/ksql/info')
  },

  // 健康检查
  async healthCheck(): Promise<{ healthy: boolean; details?: any; error?: string }> {
    return api.get('/ksql/healthcheck')
  },

  // 获取状态
  async getStatus(): Promise<any> {
    return api.get('/ksql/status')
  },

  // 执行流查询
  async executeStreamQuery(sql: string, properties?: Record<string, any>): Promise<any> {
    return api.post('/ksql/query/stream', { sql, properties })
  },

  // 终止查询
  async terminateQuery(queryId: string): Promise<{ success: boolean; message: string }> {
    return api.delete(`/ksql/query/${queryId}`)
  }
}
